package com.xjl.app.domain.service;

import com.alibaba.fastjson2.JSON;
import com.xjl.app.domain.EntityDO.DevicesCallBackMessageDO;
import com.xjl.app.domain.convert.DeviceCallBackMessageDOConcert;
import com.xjl.app.infra.entity.DevicesCallBackMessage;
import com.xjl.app.infra.service.DevicesCallBackMessageService;
import com.xjl.app.mq.sender.AiAlarmTestSender;
import com.xjl.common.redis.utils.StringRedisTemplateProxy;
import com.xjl.tools.AtomicQueue;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@RequiredArgsConstructor
public class DeviceCallBackMessageDOService {

    private final DevicesCallBackMessageService devicesCallBackMessageService;
    private final DeviceCallBackMessageDOConcert instance = DeviceCallBackMessageDOConcert.INSTANCE;
    private final ThreadPoolExecutor mQMessageThreadPool;
    private final AtomicQueue<DevicesCallBackMessage> atomicQueue = new AtomicQueue<>();
    private final AiAlarmTestSender aiAlarmTestSender;
    private final StringRedisTemplateProxy stringRedisTemplateProxy;
    @Value("${redisKey.app.message:}")
    private String messageCachekey;

    //callback消息缓冲线程
    public boolean cacheMessage(DevicesCallBackMessage message) {
        try{
            boolean push = atomicQueue.push(message);
            if(push){
                return true;
            }
            message.setCreatedTime(new Date());
            stringRedisTemplateProxy.put(messageCachekey+message.getCreatedTime().getTime(), JSON.toJSONString(message),2*60, TimeUnit.SECONDS);
            log.error("消息缓冲失败,添加进缓存 {},key = {}",message,messageCachekey+message.getCreatedTime().getTime());

            return false;
        }catch (Exception e){
            log.error("告警发送失败 {}",e.getMessage() );
            throw new RuntimeException(e);
        }
    }

    //callback消息发送线程
    public boolean sendMessage() {
        DevicesCallBackMessage pop = atomicQueue.pop();
        if(pop!=null){
            String jsonString = JSON.toJSONString(pop);
            return aiAlarmTestSender.sendAndCallBack(jsonString);
        }
        return false;
    }

    //消息入队出队
    public boolean callback(DevicesCallBackMessageDO devicesCallBackMessageDO) {
        DevicesCallBackMessage message = instance.deviceDTOtoDeviceDO(devicesCallBackMessageDO);
        try{
            mQMessageThreadPool.execute(() -> {
                if (cacheMessage(message)) {
                    sendMessage();
                }
            });

        }catch (Exception e){
            log.error(e.getMessage());
            return false;
        }
        return true;
    }


}
